package com.zoweunion.mechanic.controller.order;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.base.AuthDao;
import com.zoweunion.mechanic.entity.OrderExportBean;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.plugins.shiro.JWTUtil;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.service.order.KFOrderService;
import com.zoweunion.mechanic.util.ExcelUtils;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.UuidUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
 * 客服工单控制层
 * @author Administrator
 */
@RestController
@RequestMapping("/kfOrder")
@SuppressWarnings("unchecked")
public class KFOrderController extends BaseController{

	@Autowired
	private KFOrderService kFOrderService;
	@Autowired
	private AppService appService;
    @Autowired
    private UserService userService;
	@Autowired
	private JiguangPush jiguangPush;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private AppDao appDao;
	@Autowired
	private AuthDao authDao;

	/**
	 * 获取待受理列表(分页,条件模糊,排序)
	 * @throws MyException
	 */
	@PostMapping("/dslList")
	public ResponseBean dslList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_待受理列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		reqMap.put("s_id", user.getS_id());

		reqMap.put("order_statuses",new int[]{Constants.ORDER_STATUS_DSL});

		reqMap.put("user", user);
		// 获取当前用户的管辖区域
		if (!Constants.ROLE_GLY.equals(user.getR_id())) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
		}
		Map<String, Object> resultMap=kFOrderService.listByStatus(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取待回款列表(分页,条件模糊,排序)
	 * @throws MyException
	 */
	@PostMapping("/dhkList")
	public ResponseBean dhkList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_待回款列表");

		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

		User user = getCurrentUser(request);

		reqMap.put("s_id", user.getS_id());

		reqMap.put("rc_status","2");
		reqMap.put("user", user);

		logAfter(logger);

		// 获取当前用户的管辖区域
		if (!Constants.ROLE_GLY.equals(user.getR_id())) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
		}

		Map<String, Object> resultMap=kFOrderService.listByStatus(reqMap);

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取已听诊列表(分页,条件模糊,排序)
	 * @throws MyException
	 */
	@PostMapping("/ytzList")
	public ResponseBean ytzList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_已听诊工单列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		int[]order_statuses={Constants.ORDER_STATUS_YTZ};
		reqMap.put("order_statuses",order_statuses);
		Map<String, Object> resultMap=kFOrderService.listByStatus(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取客服工单历史列表(分页,条件模糊,排序)
	 * @throws MyException
	 */
	@PostMapping("/kfHistoryList")
	public ResponseBean kfHistoryList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_历史工单列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		reqMap.put("user", user);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		int[]order_statuses={Constants.ORDER_STATUS_DTZ,Constants.ORDER_STATUS_YTZ,Constants.ORDER_STATUS_PJ,Constants.ORDER_STATUS_DLL,Constants.ORDER_STATUS_YLL,
				Constants.ORDER_STATUS_QWXC,Constants.ORDER_STATUS_DDXC,Constants.ORDER_STATUS_QRFA,Constants.ORDER_STATUS_ZJ,Constants.ORDER_STATUS_HJ,
				Constants.ORDER_STATUS_WXJS,Constants.ORDER_STATUS_QRJS,Constants.ORDER_STATUS_DZF,Constants.ORDER_STATUS_QRSK,Constants.ORDER_STATUS_DPJ,Constants.ORDER_STATUS_WC,
				Constants.ORDER_STATUS_TZWC
		};
		reqMap.put("order_statuses",order_statuses);
		if (!Constants.ROLE_GLY.equals(user.getR_id())) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
		}
		Map<String, Object> resultMap=kFOrderService.listByStatus(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	@GetMapping("/exportHistoryList")
    public void exportHistoryList(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) throws Exception{
	    logBefore(logger, "客服历史工单导出");
        String user_account = JWTUtil.getUsername(params.get("authorization").toString());
        User user = userService.getUserByAccount(user_account);
        params.put("user", user);
        params.put("s_id", user.getS_id());

        int[]order_statuses={Constants.ORDER_STATUS_DTZ,Constants.ORDER_STATUS_YTZ,Constants.ORDER_STATUS_PJ,Constants.ORDER_STATUS_DLL,Constants.ORDER_STATUS_YLL,
                Constants.ORDER_STATUS_QWXC,Constants.ORDER_STATUS_DDXC,Constants.ORDER_STATUS_QRFA,Constants.ORDER_STATUS_ZJ,Constants.ORDER_STATUS_HJ,
                Constants.ORDER_STATUS_WXJS,Constants.ORDER_STATUS_QRJS,Constants.ORDER_STATUS_DZF,Constants.ORDER_STATUS_QRSK,Constants.ORDER_STATUS_DPJ,Constants.ORDER_STATUS_WC,
				Constants.ORDER_STATUS_TZWC
        };
        params.put("order_statuses",order_statuses);
        if (!Constants.ROLE_GLY.equals(user.getR_id())) {
            params.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
        }
//        Map<String, Object> resultMap=kFOrderService.listByStatus(reqMap);
        List<OrderExportBean> orderExport = kFOrderService.exportHistoryList(params);
        logAfter(logger);
        ExcelUtils.exportExcelToTarget(response, "工单统计", orderExport, OrderExportBean.class);
//        Workbook workBook = ExcelExportUtil.exportExcel(new ExportParams(), OrderExportBean.class, orderExport);
//        workBook.setSheetName(0, "测试导出");
//        FileUtils.downFile(workBook, "测试导出", request, response);
    }

	/**
	 * 获取故障类型列表
	 * @throws MyException
	 */
	@PostMapping("/faultList")
	public ResponseBean faultList(HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_获取故障类型列表");
		Map<String,Object> reqMap =new HashMap<String,Object>();
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		List<Map<String, Object>> resultMap=kFOrderService.getfaultList(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	/**
	 * 新建工单-PC端
	 */
	@PostMapping("/createOrder")
	public ResponseBean createOrder(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_PC端创建工单");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		if(getCurrentUser(request).getR_id().equals("1")){
			reqMap.put("u_s_id", getCurrentUser(request).getId());
		}
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		String orderId =kFOrderService.createOrder(reqMap);
		if(StringUtils.isNotBlank(orderId)) {
			//获取客服列表推送工单
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",orderId);
		}

		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}


	/**
	 * 工单加急
	 * @param str order_id
	 * @param request
	 * @return
	 * @throws MyException
	 */
	/*	@PostMapping("/urgent")
	public ResponseBean urgent(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_工单加急");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("update_user", getCurrentUser(request).getId());
		reqMap.put("urgent",1);
		int result=kFOrderService.updateOrderInfo(reqMap);
		if(result>0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}*/


	/**
	 * PC
	 * 听诊分配
	 * @param str 包含 u_t_id  order_id order_status=03
	 */
	@PostMapping("/chooseTZ")
	public ResponseBean chooseTZ(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_听诊分配");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("u_s_id", getCurrentUser(request).getId());  //接待客服id  当前为客服操作是需要该字段

		// 如果其他客服已经处理，就不允许再处理了
		Map<String, Object> orderInfoMap1 = appDao.findOrderInfoById(reqMap);
		if(!orderInfoMap1.get("order_status").equals(2)){
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"该工单已在处理中",null);
		}

		int result=kFOrderService.updateOrderInfo(reqMap);
		if(result>0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}


	/**
	 * PC
	 * 自动听诊分配
	 * @param str 包含 u_t_id  order_id order_status=03
	 */
	@PostMapping("/autoChooseTZ")
	public ResponseBean autoChooseTZ(@RequestBody String str, HttpServletRequest request) throws MyException {

		logBefore(logger, "客服工单_听诊自动分配");

		// 自动分配听诊
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("u_s_id", getCurrentUser(request).getId());  //接待客服id  当前为客服操作是需要该字段

		// 如果其他客服已经处理，就不允许再处理了
		Map<String, Object> orderInfoMap1 = appDao.findOrderInfoById(reqMap);
		if(!orderInfoMap1.get("order_status").equals(2)){
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"该工单已在处理中",null);
		}

		// 这里自动分配听诊员人的userId,匹配给u_t_id,前端不用传了
		reqMap.put("currentRoleId",getCurrentUser(request).getR_id());
		reqMap.put("searchRoleId",Constants.ROLE_TZ);
		String tzUserId = kFOrderService.autoGetOrderUserId(reqMap);
		if(tzUserId.equals("")){
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "自动获取听诊失败", null);
		}
		reqMap.put("u_t_id",tzUserId);

		int result = kFOrderService.updateOrderInfo(reqMap);
		if (result > 0) {
			return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
	}


	/**
	 * 客服工单 获取工单详情 (已听诊)
	 * @param str 包含 order_id
	 */
	@PostMapping("/getOrderInfo")
	public ResponseBean getOrderInfo(@RequestBody String str) throws MyException{
		logBefore(logger, "客服工单_获取工单详情");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, Object> resultMap=kFOrderService.getOrderInfo(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}



	/**客服工单 确定配件 (已听诊>>待配件)
	 * @param str 包含   order_id order_status=5(待配件)  partsInfo
	 */
	@PostMapping("/chooseParts")
	public ResponseBean chooseParts(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_确定配件");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("u_s_id", getCurrentUser(request).getId()); //接待客服id  当前为客服操作时需要该字段
		int result=kFOrderService.updateOrderInfo(reqMap);
		if(result>0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}


	/**
	 * 车主评价  完成工单
	 * @param str 包含 u_t_id  order_id order_status=03
	 */
	@PostMapping("/doFinish")
	public ResponseBean doFinish(@RequestBody String str){
		logBefore(logger, "客服工单_工单完成");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, Object> userInfoMap = (Map<String, Object>) reqMap.get("user_info");//移动端携带的用户信息
		reqMap.put("current_user_id", userInfoMap.get("id"));
		int result=kFOrderService.updateOrderInfo(reqMap);
		if(result>0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}


	/**
	 * 投诉处理列表
	 * @throws MyException
	 */
	@PostMapping("/complaintHandleList")
	public ResponseBean complaintList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_投诉列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id", currentUser.getS_id());
		// 获取当前用户的管辖区域
		if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(currentUser.getId(), currentUser.getS_id())));
		}
		Map<String, Object> resultMap=kFOrderService.complaintHandleList(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取投诉处理工单详情
	 */
	@PostMapping("/getComplaintHandleInfo")
	public ResponseBean getComplaintHandleInfo(@RequestBody String str){
		logBefore(logger, "客服工单_投诉详情");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, Object> resultMap=kFOrderService.getComplaintHandleInfoByOrder_id(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	/**
	 * 处理投诉工单
	 * @param str 包含 u_t_id  order_id order_status=03
	 */
	@PostMapping("/doHandleComplaint")
	public ResponseBean doHandleComplaint(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "客服工单_处理投诉工单");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		int result=kFOrderService.updateComplaint_handle(reqMap);
		if(result>0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
	}

	@PostMapping("/readExcel")
	public ResponseBean readExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws MyException{
		logBefore(logger, "excel解析");
		if (file == null) {
			throw new MyException(-1, "对象不能为空");
		}
		List<Map<String, Object>> result = kFOrderService.readExcel(file);
		logAfter(logger);
		System.out.println(new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result));
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 记录授权日志
	 * @param str
	 * @param
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/doAuthLog")
	public ResponseBean doAuthLog(@RequestBody String str) throws MyException{
		logBefore(logger, "折扣授权");
		Map<String, Object> map = JSONObject.parseObject(str, Map.class);
		int result = kFOrderService.insertAuthLog(map);
		if(result != 1) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 打折修改配件价格
	 * @param str 为json字符串
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/doDiscountSale")
	public ResponseBean doDiscountSale(@RequestBody String str, HttpServletRequest request) throws MyException{
		logBefore(logger, "折扣授权");
		// 获取当前用户的服务商id
		User currentUser = getCurrentUser(request);
		if (!(currentUser.getR_id().equals(Constants.ROLE_GG) || currentUser.getR_id().equals(Constants.ROLE_GLY))) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "权限不足");
		}
		Map<String, Object> authData = appDao.getAuthByGYId(currentUser.getId(), currentUser.getS_id());
		if (authData == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请设置折扣权限后操作");
		}
		String authStart = authData.get("change_start").toString();
		String authEnd = authData.get("change_end").toString();
		Map<String,Object> map = JSONObject.parseObject(str,Map.class);
		String order_id = map.get("order_id").toString();
		Double discount = Double.valueOf(map.get("discount").toString());
		String discountPrice = map.get("discountPrice").toString();
		//配件打折修改配件价格
		List<Map<String,Object>> PartsList = (List<Map<String, Object>>) JSONObject.parseObject(map.get("Parts").toString(),List.class);
		for(Map<String,Object> mapParts : PartsList) {
			int result = kFOrderService.updatePartsPrice(mapParts.get("p_id").toString(),mapParts.get("price").toString(), mapParts.get("discount_price").toString(),order_id);
//			if(result != 1) {
//				throw new MyException(Constants.CODE_HANDEL_FAILED,"打折修改配件价格失败");
//			}
		}
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("orderId", order_id);
		//订单折扣
		paramsMap.put("discount", discount);
		//折扣后价格
		paramsMap.put("discountPrice", discountPrice);
		orderDao.saveOrderDiscount(paramsMap);

		String context = String.format("%s将工单：%s的价格进行了优惠，优惠后价格为：%s", currentUser.getUser_name(), order_id, discountPrice);
		authDao.addAuthLog(createAuthLogAmount(currentUser.getS_id(), currentUser.getId(), context));
		//		//维修打折修改配件价格
		//		List<Map<String,Object>> repairPartsList = (List<Map<String, Object>>) JSONObject.parseObject(map.get("repairParts").toString(),Map.class);
		//		for(Map<String,Object> repairPartsmap : repairPartsList) {
		//			for(Map.Entry<String,Object> entry : repairPartsmap.entrySet()) {
		//				int result = kFOrderService.updatePartsPrice(entry.getKey(), entry.getValue().toString(),order_id);
		//				if(result != 1) {
		//					throw new MyException(Constants.CODE_HANDEL_FAILED,"打折修改配件价格失败");
		//				}
		//			}
		//		}
		//		//增减打折修改配件价格
		//		List<Map<String,Object>> zengjianPartsList = (List<Map<String, Object>>) JSONObject.parseObject(map.get("zengjianParts").toString(),Map.class);
		//		for(Map<String,Object> zengjianPartsmap : zengjianPartsList) {
		//			for(Map.Entry<String,Object> entry : zengjianPartsmap.entrySet()) {
		//				int result = kFOrderService.updatePartsPrice(entry.getKey(), entry.getValue().toString(),order_id);
		//				if(result != 1) {
		//					throw new MyException(Constants.CODE_HANDEL_FAILED,"打折修改配件价格失败");
		//				}
		//			}
		//		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	private Map<String, Object> createAuthLogAmount(String sId, String currentUserId, String context) {
		Map<String, Object> authLogParamsMap = new HashMap<>();
		authLogParamsMap.put("id", UuidUtil.get32UUID());
		authLogParamsMap.put("s_id", sId);
		authLogParamsMap.put("type", "1");
		authLogParamsMap.put("current_user_id", currentUserId);
		authLogParamsMap.put("context", context);
		return authLogParamsMap;
	}

	/**
	 * 客服/高管获取可优惠工单
	 */
	@SuppressWarnings("null")
	@PostMapping("/getDiscountOrderList")
	public ResponseBean getDiscountOrderList(@RequestBody String str, HttpServletRequest request) throws MyException{
		logBefore(logger, "客服/高管获取可优惠工单");
		Map<String,Object> map = JSONObject.parseObject(str,Map.class);
		User currentUser = getCurrentUser(request);
		String role_type = map.get("role_type").toString();
		Map<String,Object> resultObject = null;
		List<Map<String,Object>> result = null;
		List<Map<String,Object>> resultmap = new ArrayList<>();
		Map<String,Object> resultMapObj = new HashMap<>();
		LinkedHashSet<String> set = new LinkedHashSet<>();
		List<String> strlist =new ArrayList<String>();
		// 获取当前用户的管辖区域
		if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
			map.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(currentUser.getId(), currentUser.getS_id())));
		}
		if ("insideKF".equals(role_type)) {
			resultObject = kFOrderService.getDiscountOrderList(map);
			result = (List<Map<String, Object>>) resultObject.get("orderList");
			for(Map<String,Object> map1 : result) {
				set.add(map1.get("id").toString());
			}
			strlist.addAll(set);
			for(String order_id : strlist) {
				StringBuilder stringBuilder = new StringBuilder();
				List<Map<String,Object>> mapList = kFOrderService.getOrderInfoByOrderId(order_id);
				for (int i = 0; i < mapList.size(); i++) {
					stringBuilder.append(mapList.get(i).get("dictionaries_type").toString());
				}

				if(mapList.size() > 0) {
					mapList.get(0).put("dictionaries_type1", stringBuilder.toString());
				}

				Map<String,Object> map3 = mapList.size() > 0 ? mapList.get(0) : new HashMap<>();
				StringBuffer stringBuffer = new StringBuffer();
				for(Map<String,Object> map2 : result) {
					if (order_id.equals(map2.get("id").toString())) {
						map3 = map2;
						stringBuffer.append(map2.get("dictionaries_name").toString()+",");
//						map3.put("id", map2.get("id").toString());
//						map3.put("order_id", map2.get("id").toString());
//						map3.put("order_no", map2.get("order_no").toString());
//						//map3.put("user_name", map2.get("order_no").toString());
//						//map3.put("dictionaries_type", map2.get("dictionaries_type").toString());
//						map3.put("repairmanInfo", map2.get("repairmanInfo"));
//						map3.put("tzInfo", map2.get("tzInfo"));
//						map3.put("create_time", map2.get("create_time").toString());
//						map3.put("order_type", map2.get("order_type").toString());
						map3.put("dictionaries_name", stringBuffer);
					}
				};
				resultmap.add(map3);
			}
		}else if("insideGG".equals(role_type)) {
			resultObject = kFOrderService.getDiscountOrderList(map);
			result = (List<Map<String, Object>>) resultObject.get("orderList");
			for(Map<String,Object> map1 : result){
				set.add(map1.get("id").toString());
			}
			strlist.addAll(set);
			for(String order_id : strlist) {
				StringBuilder stringBuilder = new StringBuilder();
				List<Map<String,Object>> mapList = kFOrderService.getOrderInfoByOrderId(order_id);
				for (int i = 0; i < mapList.size(); i++) {
					stringBuilder.append(mapList.get(i).get("dictionaries_type").toString());
				}

				if(mapList.size() > 0) {
					mapList.get(0).put("dictionaries_type1", stringBuilder.toString());
				}

				Map<String,Object> map3 = mapList.size() > 0 ? mapList.get(0) : new HashMap<>();
				StringBuffer stringBuffer = new StringBuffer();
				for(Map<String,Object> map2 : result) {
					if (order_id.equals(map2.get("id").toString())) {
						map3 = map2;
						stringBuffer.append(map2.get("dictionaries_name").toString()+",");
//						map3.put("id", map2.get("id").toString());
//						map3.put("order_id", map2.get("id").toString());
//						map3.put("order_no", map2.get("order_no").toString());
//						//map3.put("user_name", map2.get("order_no").toString());
//						//map3.put("dictionaries_type", map2.get("dictionaries_type").toString());
//						map3.put("repairmanInfo", map2.get("repairmanInfo"));
//						map3.put("tzInfo", map2.get("tzInfo"));
//						map3.put("create_time", map2.get("create_time").toString());
//						map3.put("order_type", map2.get("order_type").toString());
						map3.put("dictionaries_name", stringBuffer);
					}
				};
				resultmap.add(map3);
			}
		}
		resultMapObj.put("list",resultmap);
		resultMapObj.put("total",resultObject.get("total"));
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", resultMapObj);
	}

	/**
	 * 客服根据工单ID获取工单详情
	 */
	@PostMapping("/getOrderDetail")
	public ResponseBean getOrderDetail(@RequestBody String str) throws MyException{
		logBefore(logger, "客服根据工单ID获取工单详情");
		Map<String,Object> map = JSONObject.parseObject(str, Map.class);
		List<Map<String,Object>> result = kFOrderService.getOrderDetail(map.get("order_id").toString());
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 客服根据工单ID获取工单配件详情
	 */
	@PostMapping("/getOrderPartsDetail")
	public ResponseBean getOrderPartsDetail(@RequestBody String order_id) throws MyException{
		logBefore(logger, "客服根据工单ID获取工单详情");
		Map<String,Object> reqmap = JSONObject.parseObject(order_id,Map.class);
		List<Map<String,Object>> result = kFOrderService.getOrderPartsDetail(reqmap.get("order_id").toString());
		//用来添加增减标识为增加类型的配件信息
		List<Map<String,Object>> addList = new ArrayList<Map<String,Object>>();
		//用来添加增减标识为减少类型的配件信息
		List<Map<String,Object>> reduceList = new ArrayList<Map<String,Object>>();
		//用来添加增减标识为原始类型的或者新增类型的配件信息
		List<Map<String,Object>> originalList = new ArrayList<Map<String,Object>>();
		//将各种类型的配件进行分类
		for(Map<String,Object> map : result) {
			if (Integer.parseInt(map.get("change_flag").toString()) == 1) {
				addList.add(map);
			}else if (Integer.parseInt(map.get("change_flag").toString()) == 2) {
				reduceList.add(map);
			}else{
				originalList.add(map);
			}
		}
		//将配件类型为增加的配件与原始类型编码相同的配件进行数量的相加
		for(Map<String,Object> originalMap : originalList) {
			for(Map<String,Object> addMap : addList) {
				if (originalMap.get("code") != null && addMap.get("code") != null) {
					if (originalMap.get("code").toString().equals(addMap.get("code").toString())) {
						originalMap.put("quantity", Integer.parseInt(originalMap.get("quantity").toString())+Integer.parseInt(addMap.get("quantity_change").toString()));
					}
				}
			}
		}
		//将配件类型为减少的配件与原始类型编码相同的配件进行数量的相减
		for(Map<String,Object> originalMap : originalList) {
			for(Map<String,Object> reduceMap : reduceList) {
				if (originalMap.get("code") != null && reduceMap.get("code") != null) {
					if (originalMap.get("code").toString().equals(reduceMap.get("code").toString())) {
						originalMap.put("quantity", Integer.parseInt(originalMap.get("quantity").toString())-Integer.parseInt(reduceMap.get("quantity_change").toString()));
					}
				}
			}
		}

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",originalList);
	}


	/**
	 * 根据客服选择的可优惠的配件信息筛选出相应的工单,然后推送给高管
	 */
	@PostMapping("/getDiscountOrderByPartsAndPush")
	public ResponseBean getDiscountOrderByPartsAndPush(@RequestBody String str) throws MyException{
		logBefore(logger, "折扣授权");
		Map<String,Object> reqmap = JSONObject.parseObject(str,Map.class);
		String order_id = reqmap.get("order_id").toString();
		Object obj = Optional.ofNullable(reqmap.get("user_id")).orElseGet(() -> {

				return reqmap.get("user_id").toString();

		});
		String g_id = obj.toString();
		List<String> strList = JSONObject.parseObject(reqmap.get("str").toString(),List.class);
		if(str != null && strList.size() > 0) {
			for(String pid : strList) {
				Map<String,Object> resultMap = kFOrderService.getDiscountOrderListByParts(pid,order_id);
				resultMap.put("g_id",g_id);
				int result = kFOrderService.handleFlag(resultMap);
				if (result != 1) {
					throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
				}
			}
		}else {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"请选择需要打折的配件",null);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);

	}

	/**
	 * 高管获取可优惠工单信息
	 */
	@PostMapping("/getDiscountOrderInfo")
	public ResponseBean getDiscountOrderInfo(@RequestBody String str) throws MyException{
		logBefore(logger, "客服根据工单ID获取工单详情");
		Map<String,Object> reqmap = JSONObject.parseObject(str, Map.class);
		String order_id = reqmap.get("order_id").toString();
		List<Map<String,Object>> result = kFOrderService.getDiscountOrderInfo(order_id);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 客服点击推送将相应订单信息通过极光推送平台推送给高管
	 */
	@PostMapping("/jPush")
	public ResponseBean jPush(@RequestBody String str) throws MyException{
		logBefore(logger, "客服点击推送将相应订单信息通过极光推送平台推送给高管");
		Map<String,Object> reqmap = JSONObject.parseObject(str,Map.class);
		String alias = reqmap.get("alias").toString();
		String alert = reqmap.get("alert").toString();
		PushResult pushResult = jiguangPush.jiguangPush(alias,alert, PushConstants.KEY_ORDER_ID, reqmap.get("order_id").toString());
		if(pushResult != null && pushResult.isResultOK()){
			return new ResponseBean(Constants.CODE_SUCCESS,"消息推送成功",pushResult);
		}else{
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"消息推送失败",null);
		}
	}

	/**
	 * 获取工单配件
	 * @param str
	 * @param request
	 * @return
	 */
	@PostMapping("/detailPartsInfo")
	public ResponseBean detailPartsInfo(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "获取工单配件");
		Map<String,Object> remap = JSONObject.parseObject(str,Map.class);
		Map<String, Object> resultMap=kFOrderService.detailPartsInfo(remap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取车主列表
	 * @param str
	 * @param request
	 * @return
	 */
	@PostMapping("/listCarMaster")
	public ResponseBean listCarMaster(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取车主列表");
		User currentUser = getCurrentUser(request);
		Map<String, Object> remap = JSONObject.parseObject(str, Map.class);
		List<Map<String, Object>> resultMap = kFOrderService.listCarMaster(currentUser, remap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}
}
